{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction to GNNs with PyTorch Geometric\n",
    "\n",
    "In this short notebook, the goal is to provide a introductory guide to get started with Graph Neural Networks using the popular library called [PyTorch Geometric](https://pytorch-geometric.readthedocs.io/en/latest/index.html). PyTorch Geometric is a PyTorch based libary hence we will be using PyTorch in this tutorial. \n",
    "\n",
    "The code used in this tutorial has been adapted from their official [examples](https://pytorch-geometric.readthedocs.io/en/latest/notes/introduction.html). I have incorporated a bit more beginner-friendly guidance and kept it minimal."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11.3\n"
     ]
    }
   ],
   "source": [
    "# Find the CUDA version PyTorch was installed with\n",
    "!python -c \"import torch; print(torch.version.cuda)\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.11.0\n"
     ]
    }
   ],
   "source": [
    "# PyTorch version\n",
    "!python -c \"import torch; print(torch.__version__)\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Install the follow packages but make sure to \n",
    "\n",
    "---\n",
    "\n",
    "install the right version below. Find more instructions [here](https://pytorch-geometric.readthedocs.io/en/latest/notes/installation.html) if you get lost. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in links: https://data.pyg.org/whl/torch-1.11.0.html\n",
      "Collecting torch-scatter\n",
      "  Downloading torch_scatter-2.0.9.tar.gz (21 kB)\n",
      "Building wheels for collected packages: torch-scatter\n",
      "  Building wheel for torch-scatter (setup.py) ... \u001b[?25ldone\n",
      "\u001b[?25h  Created wheel for torch-scatter: filename=torch_scatter-2.0.9-cp38-cp38-linux_x86_64.whl size=304063 sha256=f9cc42222b3244636f8cb1a257bdc1556f9292207d987b02ec79e7fb59689fdb\n",
      "  Stored in directory: /home/codespace/.cache/pip/wheels/7c/51/2a/409339f45a48bf748a5db76dfa11373ea7c883ecf1932eee2f\n",
      "Successfully built torch-scatter\n",
      "Installing collected packages: torch-scatter\n",
      "Successfully installed torch-scatter-2.0.9\n"
     ]
    }
   ],
   "source": [
    "!pip install torch-scatter -f https://data.pyg.org/whl/torch-1.11.0.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in links: https://data.pyg.org/whl/torch-1.11.0.html\n",
      "Collecting torch-sparse\n",
      "  Downloading torch_sparse-0.6.13.tar.gz (48 kB)\n",
      "\u001b[K     |████████████████████████████████| 48 kB 1.7 MB/s  eta 0:00:01\n",
      "\u001b[?25hCollecting scipy\n",
      "  Downloading scipy-1.8.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (41.6 MB)\n",
      "\u001b[K     |████████████████████████████████| 41.6 MB 73.5 MB/s eta 0:00:01\n",
      "\u001b[?25hRequirement already satisfied: numpy<1.25.0,>=1.17.3 in /home/codespace/.conda/envs/gnn/lib/python3.8/site-packages (from scipy->torch-sparse) (1.22.3)\n",
      "Building wheels for collected packages: torch-sparse\n",
      "  Building wheel for torch-sparse (setup.py) ... \u001b[?25ldone\n",
      "\u001b[?25h  Created wheel for torch-sparse: filename=torch_sparse-0.6.13-cp38-cp38-linux_x86_64.whl size=570934 sha256=27a158cb7be5e10bb7846cce70764338cbb12828ea70eaf5a41a79f15cfc60c3\n",
      "  Stored in directory: /home/codespace/.cache/pip/wheels/81/94/1a/3fd0c022a887c997c5e681961f2bd2e41f8fd6b66562b90fb6\n",
      "Successfully built torch-sparse\n",
      "Installing collected packages: scipy, torch-sparse\n",
      "Successfully installed scipy-1.8.1 torch-sparse-0.6.13\n"
     ]
    }
   ],
   "source": [
    "!pip install torch-sparse -f https://data.pyg.org/whl/torch-1.11.0.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting torch-geometric\n",
      "  Downloading torch_geometric-2.0.4.tar.gz (407 kB)\n",
      "\u001b[K     |████████████████████████████████| 407 kB 26.9 MB/s eta 0:00:01\n",
      "\u001b[?25hCollecting tqdm\n",
      "  Downloading tqdm-4.64.0-py2.py3-none-any.whl (78 kB)\n",
      "\u001b[K     |████████████████████████████████| 78 kB 1.8 MB/s  eta 0:00:01\n",
      "\u001b[?25hRequirement already satisfied: numpy in /home/codespace/.conda/envs/gnn/lib/python3.8/site-packages (from torch-geometric) (1.22.3)\n",
      "Requirement already satisfied: scipy in /home/codespace/.conda/envs/gnn/lib/python3.8/site-packages (from torch-geometric) (1.8.1)\n",
      "Collecting pandas\n",
      "  Downloading pandas-1.4.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.7 MB)\n",
      "\u001b[K     |████████████████████████████████| 11.7 MB 79.4 MB/s eta 0:00:01\n",
      "\u001b[?25hCollecting jinja2\n",
      "  Downloading Jinja2-3.1.2-py3-none-any.whl (133 kB)\n",
      "\u001b[K     |████████████████████████████████| 133 kB 87.1 MB/s eta 0:00:01\n",
      "\u001b[?25hRequirement already satisfied: requests in /home/codespace/.conda/envs/gnn/lib/python3.8/site-packages (from torch-geometric) (2.27.1)\n",
      "Collecting pyparsing\n",
      "  Using cached pyparsing-3.0.9-py3-none-any.whl (98 kB)\n",
      "Collecting scikit-learn\n",
      "  Downloading scikit_learn-1.1.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (31.2 MB)\n",
      "\u001b[K     |████████████████████████████████| 31.2 MB 84.1 MB/s eta 0:00:01\n",
      "\u001b[?25hCollecting MarkupSafe>=2.0\n",
      "  Downloading MarkupSafe-2.1.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (25 kB)\n",
      "Collecting pytz>=2020.1\n",
      "  Downloading pytz-2022.1-py2.py3-none-any.whl (503 kB)\n",
      "\u001b[K     |████████████████████████████████| 503 kB 69.2 MB/s eta 0:00:01\n",
      "\u001b[?25hRequirement already satisfied: python-dateutil>=2.8.1 in /home/codespace/.conda/envs/gnn/lib/python3.8/site-packages (from pandas->torch-geometric) (2.8.2)\n",
      "Requirement already satisfied: six>=1.5 in /home/codespace/.conda/envs/gnn/lib/python3.8/site-packages (from python-dateutil>=2.8.1->pandas->torch-geometric) (1.16.0)\n",
      "Requirement already satisfied: charset-normalizer~=2.0.0 in /home/codespace/.conda/envs/gnn/lib/python3.8/site-packages (from requests->torch-geometric) (2.0.4)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /home/codespace/.conda/envs/gnn/lib/python3.8/site-packages (from requests->torch-geometric) (3.3)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /home/codespace/.conda/envs/gnn/lib/python3.8/site-packages (from requests->torch-geometric) (2022.5.18.1)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /home/codespace/.conda/envs/gnn/lib/python3.8/site-packages (from requests->torch-geometric) (1.26.9)\n",
      "Collecting joblib>=1.0.0\n",
      "  Downloading joblib-1.1.0-py2.py3-none-any.whl (306 kB)\n",
      "\u001b[K     |████████████████████████████████| 306 kB 78.1 MB/s eta 0:00:01\n",
      "\u001b[?25hCollecting threadpoolctl>=2.0.0\n",
      "  Downloading threadpoolctl-3.1.0-py3-none-any.whl (14 kB)\n",
      "Building wheels for collected packages: torch-geometric\n",
      "  Building wheel for torch-geometric (setup.py) ... \u001b[?25ldone\n",
      "\u001b[?25h  Created wheel for torch-geometric: filename=torch_geometric-2.0.4-py3-none-any.whl size=616602 sha256=c3dd839f53e4c307e7a223cb3868bbe2dfc5bb5a5586c2f1bcfe5d2f20f6d6a6\n",
      "  Stored in directory: /home/codespace/.cache/pip/wheels/c1/be/e9/b90ded2a496c975a539af002fe1f0f2a22a97af13b41866d6e\n",
      "Successfully built torch-geometric\n",
      "Installing collected packages: threadpoolctl, pytz, MarkupSafe, joblib, tqdm, scikit-learn, pyparsing, pandas, jinja2, torch-geometric\n",
      "Successfully installed MarkupSafe-2.1.1 jinja2-3.1.2 joblib-1.1.0 pandas-1.4.2 pyparsing-3.0.9 pytz-2022.1 scikit-learn-1.1.1 threadpoolctl-3.1.0 torch-geometric-2.0.4 tqdm-4.64.0\n"
     ]
    }
   ],
   "source": [
    "!pip install torch-geometric"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Getting Started\n",
    "\n",
    "Import PyTorch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.11.0\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "# print torch version\n",
    "print(torch.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The great thing about PyTorch Geometric is that it contain useful functionalities to import and load graph related data. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch_geometric.data import Data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's create an unweighted and undirected graph with three nodes and four total edges."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Data(x=[3, 1], edge_index=[2, 4])\n"
     ]
    }
   ],
   "source": [
    "# define edge list\n",
    "edge_index = torch.tensor([[0, 1, 1, 2], [1, 0, 2, 1]], dtype=torch.long)\n",
    "\n",
    "# define node features\n",
    "x = torch.tensor([[-1], [0], [1]])\n",
    "\n",
    "# create graph data object\n",
    "data = Data(x=x, edge_index=edge_index)\n",
    "print(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our data object `Data` has many useful utility functions to check the properties of the graph. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n"
     ]
    }
   ],
   "source": [
    "# check number of edges of the graph\n",
    "print(data.num_edges)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "# check number of nodes of the graph\n",
    "print(data.num_nodes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "# check number of features of the graph\n",
    "print(data.num_features)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n"
     ]
    }
   ],
   "source": [
    "# check if graph is directed\n",
    "print(data.is_directed())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loading Data\n",
    "\n",
    "Find more fun functions related to graph data [here](https://pytorch-geometric.readthedocs.io/en/latest/modules/data.html#torch_geometric.data.Data). \n",
    "\n",
    "One of the cool things about the PyTorch Geometric library is that it contains out-of-the-box benchmark datasets that are ready to use and explore. A popular dataset is the Cora dataset that is used for supervised graph node classification. (We will talk about these applications in an upcoming tutorial but for now we will focus on the data itself).\n",
    "\n",
    "\"The Cora dataset consists of 2708 scientific publications classified into one of seven classes. The citation network consists of 5429 links. Each publication in the dataset is described by a 0/1-valued word vector indicating the absence/presence of the corresponding word from the dictionary. The dictionary consists of 1433 unique words.\" - [Papers with Code](https://paperswithcode.com/dataset/cora).\n",
    "\n",
    "Let's load the Cora dataset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Downloading https://github.com/kimiyoung/planetoid/raw/master/data/ind.cora.x\n",
      "Downloading https://github.com/kimiyoung/planetoid/raw/master/data/ind.cora.tx\n",
      "Downloading https://github.com/kimiyoung/planetoid/raw/master/data/ind.cora.allx\n",
      "Downloading https://github.com/kimiyoung/planetoid/raw/master/data/ind.cora.y\n",
      "Downloading https://github.com/kimiyoung/planetoid/raw/master/data/ind.cora.ty\n",
      "Downloading https://github.com/kimiyoung/planetoid/raw/master/data/ind.cora.ally\n",
      "Downloading https://github.com/kimiyoung/planetoid/raw/master/data/ind.cora.graph\n",
      "Downloading https://github.com/kimiyoung/planetoid/raw/master/data/ind.cora.test.index\n",
      "Processing...\n",
      "Done!\n"
     ]
    }
   ],
   "source": [
    "from torch_geometric.datasets import Planetoid\n",
    "\n",
    "dataset = Planetoid(root='tmp/Cora', name='Cora')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's check some of the properties of the Cora dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of graphs:  1\n",
      "Number of features:  1433\n",
      "Number of classes:  7\n"
     ]
    }
   ],
   "source": [
    "# number of graphs\n",
    "print(\"Number of graphs: \", len(dataset))\n",
    "\n",
    "# number of features\n",
    "print(\"Number of features: \", dataset.num_features)\n",
    "\n",
    "# number of classes\n",
    "print(\"Number of classes: \", dataset.num_classes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can see that this particular graph dataset only contains one graph. Graph data can be very complex and can include multiple graphs depending on the type of data and application. Let's check more feature of the Cora dataset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of nodes:  2708\n",
      "Number of edges:  10556\n",
      "Is directed:  False\n"
     ]
    }
   ],
   "source": [
    "# select the first graph\n",
    "data = dataset[0]\n",
    "\n",
    "# number of nodes\n",
    "print(\"Number of nodes: \", data.num_nodes)\n",
    "\n",
    "# number of edges\n",
    "print(\"Number of edges: \", data.num_edges)\n",
    "\n",
    "# check if directed\n",
    "print(\"Is directed: \", data.is_directed())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can sample nodes from the graph this way:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Shape of sample nodes:  torch.Size([5, 1433])\n"
     ]
    }
   ],
   "source": [
    "# sample nodes from the graph\n",
    "print(\"Shape of sample nodes: \", data.x[:5].shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We extracted 5 nodes from the graph and checked its shape. You will see that each node has `1433` features.\n",
    "\n",
    "Another great advantage of using PyTorch Geometric to load the Cora data is that it comes pre-processed and ready to use. It also has the splits for training, validation and test which we can directly use for training a GNN.\n",
    "\n",
    "Let's check some stats for the partitions of the data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# of nodes to train on:  140\n",
      "# of nodes to test on:  1000\n",
      "# of nodes to validate on:  500\n"
     ]
    }
   ],
   "source": [
    "# check training nodes\n",
    "print(\"# of nodes to train on: \", data.train_mask.sum().item())\n",
    "\n",
    "# check test nodes\n",
    "print(\"# of nodes to test on: \", data.test_mask.sum().item())\n",
    "\n",
    "# check validation nodes\n",
    "print(\"# of nodes to validate on: \", data.val_mask.sum().item())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That information is important as it will indicate to our model which nodes to train against and which to test against, and so on.\n",
    "\n",
    "When training neural networks we train them using batches of data. PyTorch Geometric provides efficient processes to load batches of data.\n",
    "\n",
    "PyTorch Geometric contains a data loader which is a very popular feature in PyTorch to efficiently load data when training neural networks.\n",
    " \n",
    "So let's try to load the data using the built in `DataLoader`:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch_geometric.datasets import Planetoid\n",
    "from torch_geometric.loader import DataLoader\n",
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cuda\n"
     ]
    }
   ],
   "source": [
    "print(device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset = Planetoid(root='tmp/Cora', name='Cora')\n",
    "data = dataset[0].to(device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Print some quick statistics about the data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "X shape:  torch.Size([2708, 1433])\n",
      "Edge shape:  torch.Size([2, 10556])\n",
      "Y shape:  torch.Size([2708])\n"
     ]
    }
   ],
   "source": [
    "print(\"X shape: \", data.x.shape)\n",
    "print(\"Edge shape: \", data.edge_index.shape)\n",
    "print(\"Y shape: \", data.y.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model and Training\n",
    "\n",
    "Finally, let's define a standard GCN to train on the Cora dataset. The aim is to train a model that gets better at predicting the class of the node.\n",
    "\n",
    "To keep thins simple we will use the same model definition as used in the [tutorial](https://pytorch-geometric.readthedocs.io/en/latest/notes/introduction.html) we adpated the code from. Note that we are using the built-in `GCNConv` model but you could easily implement your own (something we will cover in a future tutorial). \n",
    "\n",
    "The model below uses two `GCNConv` layers. The first layer is followed by a non-linearity `ReLU` and `Dropout`. The result is fed to the second layer on top of which we apply `Softmax` to get distribution over the number of classes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn.functional as F\n",
    "from torch_geometric.nn import GCNConv\n",
    "\n",
    "class GCN(torch.nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        \"\"\" GCNConv layers \"\"\"\n",
    "        self.conv1 = GCNConv(data.num_features, 16)\n",
    "        self.conv2 = GCNConv(16, dataset.num_classes)\n",
    "\n",
    "    def forward(self, data):\n",
    "        x, edge_index = data.x, data.edge_index\n",
    "        x = self.conv1(x, edge_index)\n",
    "        x = F.relu(x)\n",
    "        x = F.dropout(x, training=self.training)\n",
    "        x = self.conv2(x, edge_index)\n",
    "\n",
    "        return F.log_softmax(x, dim=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Initial model and optimizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = GCN().to(device)\n",
    "optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Define accuracy function for evaluating performance:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "# useful function for computing accuracy\n",
    "def compute_accuracy(pred_y, y):\n",
    "    return (pred_y == y).sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And finally we train the model on the trainin nodes for 200 epochs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 10, Loss: 0.8056, Training Acc: 0.9214\n",
      "Epoch: 20, Loss: 0.2925, Training Acc: 0.9500\n",
      "Epoch: 30, Loss: 0.1065, Training Acc: 1.0000\n",
      "Epoch: 40, Loss: 0.0654, Training Acc: 1.0000\n",
      "Epoch: 50, Loss: 0.0423, Training Acc: 1.0000\n",
      "Epoch: 60, Loss: 0.0467, Training Acc: 0.9929\n",
      "Epoch: 70, Loss: 0.0496, Training Acc: 0.9929\n",
      "Epoch: 80, Loss: 0.0353, Training Acc: 0.9929\n",
      "Epoch: 90, Loss: 0.0397, Training Acc: 1.0000\n",
      "Epoch: 100, Loss: 0.0253, Training Acc: 1.0000\n",
      "Epoch: 110, Loss: 0.0353, Training Acc: 0.9929\n",
      "Epoch: 120, Loss: 0.0340, Training Acc: 1.0000\n",
      "Epoch: 130, Loss: 0.0338, Training Acc: 1.0000\n",
      "Epoch: 140, Loss: 0.0319, Training Acc: 1.0000\n",
      "Epoch: 150, Loss: 0.0469, Training Acc: 0.9929\n",
      "Epoch: 160, Loss: 0.0260, Training Acc: 0.9929\n",
      "Epoch: 170, Loss: 0.0392, Training Acc: 0.9857\n",
      "Epoch: 180, Loss: 0.0470, Training Acc: 0.9929\n",
      "Epoch: 190, Loss: 0.0267, Training Acc: 0.9929\n",
      "Epoch: 200, Loss: 0.0221, Training Acc: 1.0000\n"
     ]
    }
   ],
   "source": [
    "# train the model\n",
    "model.train()\n",
    "losses = []\n",
    "accuracies = []\n",
    "for epoch in range(200):\n",
    "    optimizer.zero_grad()\n",
    "    out = model(data)\n",
    "\n",
    "    loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask])\n",
    "    correct = compute_accuracy(out.argmax(dim=1)[data.train_mask], data.y[data.train_mask])\n",
    "    acc = int(correct) / int(data.train_mask.sum())\n",
    "    losses.append(loss.item())\n",
    "    accuracies.append(acc)\n",
    "\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "    if (epoch+1) % 10 == 0:\n",
    "        print('Epoch: {}, Loss: {:.4f}, Training Acc: {:.4f}'.format(epoch+1, loss.item(), acc))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXoAAAD4CAYAAADiry33AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMiwgaHR0cHM6Ly9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qvm1yRSRL0TkIxH5ihfi6ey9Gyz77CvAUWPMfpeyAd9fHXJEvx1nvpLoBx0RiQT+DfzQGFMD/A0YBUwHirB+NnrDWcaYmcAi4AcicrbrRGP9VvRKn1uxBra5HPiXs2iw7LN23tw/3RGRn2ON+fC8s6gIGGGMmQHcBbwgIkMGMKRB9951cDUnVigGfH91kiPaefo485VEP6iGLBSRIKw38HljzMsAxpijxhi7McYB/IN++rnaE2NMofN/CfCKM46jbT8Fnf9LvBEb1pfPFmPMUWeMg2Kf0fX+GRTHnYjcCFwKXONMEDibRsqdjzdjtYWPHaiYunnvvL7PxBru9OvAi21lA72/OssR9ONx5iuJ3p3hDgeEs+3vCWCPMeZPLuWubWpXAjs7LjsAsUWISFTbY6wTeTs5cSjIG4DXBjo2pxNqWYNhnzl1tX9WA9c7e0XMA6pdfnoPCBFZCPwPcLkxpsGlPFFEApyPR2IN43lwAOPq6r0bDMOLng98aYwpaCsYyP3VVY6gP4+zgTjLPBB/WGem92F9E//ci3GchfWTazuw1fl3MfAssMNZvhpI9kJsI7F6PGwDdrXtJyAeeB/YD7wHxHkhtgisAeWjXcoGfJ9hfdEUAS1YbaE3dbV/sHpBPOo85nYAWV6ILQer/bbtWHvMOe9i53u8FdgCXDbAcXX53gE/d+6zvcCigYzLWf4UcEuHeQdyf3WVI/rtONNbICillI/zlaYbpZRSXdBEr5RSPk4TvVJK+ThN9Eop5eM00SullI/TRK+UUj5OE71SSvm4/w+0CMI9zq535AAAAABJRU5ErkJggg==",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# plot the loss and accuracy\n",
    "import matplotlib.pyplot as plt\n",
    "plt.plot(losses)\n",
    "plt.plot(accuracies)\n",
    "plt.legend(['Loss', 'Accuracy'])\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It looks like the model achieves a very high accuracy and small loss on the training dataset. To see how well it generalizes, let's test on the testing nodes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy: 0.7870\n"
     ]
    }
   ],
   "source": [
    "# evaluate the model on test set\n",
    "model.eval()\n",
    "pred = model(data).argmax(dim=1)\n",
    "correct = compute_accuracy(pred[data.test_mask], data.y[data.test_mask])\n",
    "acc = int(correct) / int(data.test_mask.sum())\n",
    "print(f'Accuracy: {acc:.4f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Very cool! It seems we got a very nice accuracy for the test as well. Our model is doing okay. There are many ways you can go about trying to improve this model, but we will keep that for another time. Hopefully, with this tutorial you got a glimpse of graph data and how to use PyTorch Geometric to train GNNs on a very popular dataset. \n",
    "\n",
    "Note that I haven't tested if this code works with GPUs. I will leave that as an exercise for the learner. \n",
    "\n",
    "If you are interested in the full tutorial and more examples, visit the [PyTorch Geomtric documentation](https://pytorch-geometric.readthedocs.io/en/latest/notes/introduction.html) where I adapted the code from. \n",
    "\n",
    "Feel free to reach out on [Twitter](https://twitter.com/omarsar0) if you have any further questions."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.12 ('base')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "d4d1e4263499bec80672ea0156c357c1ee493ec2b1c70f0acce89fc37c4a6abe"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
